<!DOCTYPE html>
<html>
<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>传智健康 - 套餐管理</title>
    <meta name="description" content="传智健康">
    <meta name="keywords" content="传智健康">
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../plugins/elementui/index.css">
    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <style>
        .app-container {
            padding: 20px;
        }
        .filter-container {
            margin-bottom: 20px;
        }
        .pagination-container {
            margin-top: 20px;
            text-align: right;
        }
        .el-table {
            width: 100%;
        }
        .el-dialog {
            min-width: 600px;
        }
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    </style>
</head>
<body class="hold-transition">
<div id="app">
    <div class="content-header">
        <h1>预约管理<small>套餐管理</small></h1>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>预约管理</el-breadcrumb-item>
            <el-breadcrumb-item>套餐管理</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <div class="app-container">
        <div class="box">
            <div class="filter-container">
                <el-input placeholder="套餐编码/套餐名称" v-model="pagination.queryString" style="width: 200px;" class="filter-item" @keyup.enter.native="findPage"></el-input>
                <el-button @click="findPage()" class="dalfBut" type="primary" icon="el-icon-search">查询</el-button>
                <el-button type="primary" class="butT" @click="handleCreate()" icon="el-icon-plus">新建</el-button>
            </div>
            <el-table
                    size="small"
                    :data="dataList"
                    stripe
                    highlight-current-row
                    border
                    v-loading="loading"
                    element-loading-text="拼命加载中"
                    element-loading-spinner="el-icon-loading"
                    style="width: 100%">
                <el-table-column type="index" align="center" label="序号" width="60"></el-table-column>
                <el-table-column prop="code" label="套餐编码" align="center" width="120"></el-table-column>
                <el-table-column prop="name" label="套餐名称" align="center" width="150"></el-table-column>
                <el-table-column label="适用性别" align="center" width="100">
                    <template slot-scope="scope">
                        <span>{{ scope.row.sex === '0' ? '不限' : scope.row.sex === '1' ? '男' : '女' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="age" label="适用年龄" align="center" width="120"></el-table-column>
                <el-table-column prop="price" label="价格(元)" align="center" width="100">
                    <template slot-scope="scope">
                        <span>{{ scope.row.price.toFixed(2) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="图片" align="center" width="120">
                    <template slot-scope="scope">
                        <img v-if="scope.row.img" :src="scope.row.img" style="width: 50px; height: 50px;"/>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="套餐说明" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" align="center" width="180" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleUpdate(scope.row)" icon="el-icon-edit">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)" icon="el-icon-delete">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pagination.currentPage"
                        :page-sizes="[10, 20, 30, 50]"
                        :page-size="pagination.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pagination.total">
                </el-pagination>
            </div>

            <!-- 新增弹层 -->
            <el-dialog :title="formTitle" :visible.sync="dialogFormVisible" width="50%" @close="resetForm">
                <el-form ref="dataForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="套餐编码" prop="code">
                                <el-input v-model="formData.code" placeholder="请输入套餐编码"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="套餐名称" prop="name">
                                <el-input v-model="formData.name" placeholder="请输入套餐名称"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="助记码">
                                <el-input v-model="formData.helpCode" placeholder="请输入助记码"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="适用性别">
                                <el-select v-model="formData.sex" style="width: 100%">
                                    <el-option label="不限" value="0"></el-option>
                                    <el-option label="男" value="1"></el-option>
                                    <el-option label="女" value="2"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="适用年龄">
                                <el-input v-model="formData.age" placeholder="如:18-60"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="价格(元)" prop="price">
                                <el-input v-model.number="formData.price" type="number" placeholder="请输入价格">
                                    <template slot="append">元</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="套餐图片">
                                <el-upload
                                        class="avatar-uploader"
                                        action="/setmeal/upload"
                                        :show-file-list="false"
                                        :on-success="handleAvatarSuccess"
                                        :before-upload="beforeAvatarUpload">
                                    <img v-if="formData.img" :src="formData.img" class="avatar">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="套餐说明">
                                <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="请输入套餐说明"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="注意事项">
                                <el-input v-model="formData.attention" type="textarea" :rows="2" placeholder="请输入注意事项"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- 在el-form内添加检查组选择 -->
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="包含检查组">
                                <el-select
                                        v-model="formData.checkGroupIds"
                                        multiple
                                        filterable
                                        placeholder="请选择检查组"
                                        style="width:100%">
                                    <el-option
                                            v-for="group in checkGroupOptions"
                                            :key="group.id"
                                            :label="group.name"
                                            :value="group.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveData">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</div>
</body>
<!-- 引入组件库 -->
<script src="../js/vue.js"></script>
<script src="../plugins/elementui/index.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                loading: false,
                pagination: {
                    currentPage: 1,
                    pageSize: 10,
                    total: 0,
                    queryString: null
                },
                dataList: [],
                checkGroupOptions: [], // 检查组下拉选项
                formData: {
                    id: null,
                    code: '',
                    name: '',
                    helpCode: '',
                    sex: '0',
                    age: '',
                    price: null,
                    remark: '',
                    attention: '',
                    img: '',
                    checkGroupIds: [] // 新增：选中的检查组ID数组
                },
                dialogFormVisible: false,
                formTitle: '新增套餐',
                isEdit: false,
                rules: {
                    code: [
                        { required: true, message: '请输入套餐编码', trigger: 'blur' },
                        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                    ],
                    name: [
                        { required: true, message: '请输入套餐名称', trigger: 'blur' },
                        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                    ],
                    price: [
                        { required: true, message: '请输入价格', trigger: 'blur' },
                        { type: 'number', message: '价格必须为数字值', trigger: 'blur' }
                    ]
                }

            }
        },
        created() {
            this.findPage();
            this.loadCheckGroups(); // 加载检查组选项
        },
        methods: {
            // 分页查询
            findPage() {
                this.loading = true;
                axios.post('/setmeal/findPage', this.pagination)
                    .then(response => {
                        this.loading = false;
                        if (response.data.flag) {
                            this.dataList = response.data.data.rows;
                            this.pagination.total = response.data.data.total;
                        } else {
                            this.$message.error(response.data.message);
                        }
                    })
                    .catch(error => {
                        this.loading = false;
                        this.$message.error('请求失败');
                        console.error(error);
                    });
            },

            // 保存数据（新增或编辑）
            saveData() {
                console.log("提交数据：", this.packageFormData());
                this.$refs['dataForm'].validate(valid => {
                    if (valid) {
                        const api = this.isEdit ?
                            axios.put('/setmeal/updateWithGroups', this.packageFormData()) :
                            axios.post('/setmeal/add', this.packageFormData());

                        api.then(response => {
                            if (response.data.flag) {
                                this.$message.success(response.data.message);
                                this.dialogFormVisible = false;
                                this.findPage();
                            } else {
                                this.$message.error(response.data.message);
                            }
                        }).catch(error => {
                            console.error('详细错误:', error.response);
                            let errorMsg = this.isEdit ? '更新失败' : '添加失败';
                            if (error.response && error.response.data) {
                                errorMsg += ': ' + (error.response.data.message || JSON.stringify(error.response.data));
                            }
                            this.$message.error(errorMsg);
                        });
                    }
                });
            },

            // 封装提交数据为后端需要的DTO格式
            packageFormData() {
                return {
                    setmeal: {
                        id: this.formData.id,
                        code: this.formData.code,
                        name: this.formData.name,
                        helpCode: this.formData.helpCode,  // 助记码
                        sex: this.formData.sex,           // 适用性别：0不限 1男 2女
                        age: this.formData.age,           // 适用年龄范围
                        price: this.formData.price,        // 套餐价格
                        remark: this.formData.remark,     // 套餐说明
                        attention: this.formData.attention,// 注意事项
                        img: this.formData.img            // 图片路径
                    },
                    checkGroupIds: this.formData.checkGroupIds // 关联的检查组ID数组
                };
            },

            // 删除套餐
            handleDelete(row) {
                this.$confirm(`确认删除套餐【${row.name}】吗?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete(`/setmeal/deleteWithGroups/${row.id}`)
                        .then(response => {
                            if (response.data.flag) {
                                this.$message.success(response.data.message);
                                this.findPage();
                            } else {
                                this.$message.error(response.data.message);
                            }
                        })
                        .catch(error => {
                            this.$message.error('删除失败');
                            console.error(error);
                        });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            },

            // 弹出添加窗口
            handleCreate() {
                this.dialogFormVisible = true;
                this.isEdit = false;
                this.formTitle = '新增套餐';
                this.resetForm();
            },

            // 弹出编辑窗口
            handleUpdate(row) {
                this.dialogFormVisible = true;
                this.isEdit = true;
                this.formTitle = '编辑套餐';
                // 深拷贝row对象到formData
                // 加载套餐基础数据
                this.formData = JSON.parse(JSON.stringify(row));

                // 加载关联的检查组
                axios.get(`/setmeal/getCheckGroupIds/${row.id}`)
                    .then(response => {
                        if (response.data.flag) {
                            this.formData.checkGroupIds = response.data.data;
                        }
                    });
            },

            // 重置表单
            resetForm() {
                this.formData = {
                    id: null,
                    code: '',
                    name: '',
                    helpCode: '',
                    sex: '0',
                    age: '',
                    price: null,
                    remark: '',
                    attention: '',
                    img: ''
                };
                if (this.$refs['dataForm']) {
                    this.$refs['dataForm'].clearValidate();
                }
            },

            // 图片上传成功
            handleAvatarSuccess(res, file) {
                if (res.flag) {
                    this.formData.img = res.data;
                    this.$message.success('上传成功');
                } else {
                    this.$message.error(res.message);
                }
            },

            // 图片上传前校验
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },

            // 切换页码
            handleCurrentChange(currentPage) {
                this.pagination.currentPage = currentPage;
                this.findPage();
            },

            // 改变每页条数
            handleSizeChange(pageSize) {
                this.pagination.pageSize = pageSize;
                this.findPage();
            },

            // 加载检查组下拉选项
            loadCheckGroups() {
                console.log('开始加载检查组数据...');
                axios.get('/checkgroup/listAll')
                    .then(response => {
                        console.log('检查组响应:', response.data); // 调试输出
                        if (response.data.flag) {
                            this.checkGroupOptions = response.data.data;
                        } else {
                            this.$message.error('加载检查组失败');
                        }
                    })
                    .catch(error => {
                        console.error('加载检查组异常:', error);
                        this.$message.error('无法加载检查组数据');
                    });
            }
        }
    });
</script>
</html>